package com.bang.study.query;

import org.apache.lucene.search.join.ScoreMode;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.transport.TransportClient;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.text.Text;
import org.elasticsearch.common.transport.InetSocketTransportAddress;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.index.query.QueryParseContext;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightField;
import org.elasticsearch.transport.client.PreBuiltTransportClient;

import java.net.InetAddress;
import java.util.Map;

/**
 * @ClassName: GrandParentChildQuery
 * @author: BANG
 * @Date: 2020/01/16 15:08
 * @Version: 1.0
 * @Modified By:
 * @Desc: TODO
 *
 * GET /blog_website/blogs/_search
 * {
 *   "query": {
 *     "match": {
 *       "title": "博客"
 *     }
 *   },
 *   "highlight": {
 *     "fields": {
 *       "title": {}
 *     }
 *   }
 * }
 *
 */
public class HighLightQuery {

    public static void main(String[] args) throws Exception{
        Settings settings = Settings.builder()
                .put("cluster.name", "elasticsearch")
                .put("client.transport.sniff", true)
                .build();
        TransportClient client = new PreBuiltTransportClient(settings).addTransportAddress(
                new InetSocketTransportAddress(InetAddress.getByName("localhost"), 9300)
        );

        HighlightBuilder highlightBuilder = new HighlightBuilder();
        highlightBuilder.field("title");
        SearchResponse searchResponse = client.prepareSearch("blog_website").setTypes("blogs")
                .setQuery(QueryBuilders.matchQuery("title","博客"))
                .highlighter(highlightBuilder)
                .get();
        for (SearchHit searchHit : searchResponse.getHits().getHits()) {
            Map<String, HighlightField> highlightFields = searchHit.getHighlightFields();
            for (Map.Entry<String, HighlightField> entry : highlightFields.entrySet()) {
                HighlightField value = entry.getValue();
                Text[] fragments = value.getFragments();
                for (Text fragment : fragments) {
                    System.err.println(searchHit.getId()+" : "+fragment.toString());
                }
            }
        }

        client.close();

    }
}
